# -*- coding: utf-8 -*-

# Copyright 2013 Ida Leter, adapted from Fanficdownloader
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import os, re
import urlparse
import string
from math import floor
from functools import partial
import logging
logger = logging.getLogger(__name__)
import urlparse as up

import exceptions
from configurable import Configurable

class Paper(Configurable):
    
    def __init__(self, configuration):
        Configurable.__init__(self, configuration)
        try:
            ## calibre plugin will set externally to match PI version.
            self.metadata = {'version':os.environ['CURRENT_VERSION_ID']}
        except:
            self.metadata = {'version':'1.0'}
        
    def setMetadata(self, key, value):
        self.metadata[key]=value
        
    def getMetadataRaw(self,key):
        if self.isValidMetaEntry(key) and self.metadata.has_key(key):
            return self.metadata[key]

    def getMetadata(self, key):
        value = None
        if not self.isValidMetaEntry(key):
            return value

        if self.isList(key):
            return u', '.join(self.getList(key))
        elif self.metadata.has_key(key):
            value = self.metadata[key]
            return value
        
    def getAllMetadata(self,keeplists=True):
        '''
        All single value *and* list value metadata as strings (unless keeplists=True, then keep lists).
        '''
        allmetadata = {}
        
        # special handling for authors/authorUrls
        authlinkhtml="<a class='authorlink' href='%s'>%s</a>"
        if self.isList('author'): # more than one author, assume multiple authorUrl too.
            htmllist=[]
            for i, v in enumerate(self.getList('author')):
                aurl = self.getList('authorUrl')[i]                    
                auth = v
                htmllist.append(authlinkhtml%(aurl,auth))
            self.setMetadata('authorHTML',', '.join(htmllist))
        else:
           self.setMetadata('authorHTML',authlinkhtml%(self.getMetadata('authorUrl'),
                                                       self.getMetadata('author')))

        for k in self.getValidMetaList():
            if self.isList(k) and keeplists:
                allmetadata[k] = self.getList(k)
            else:
                allmetadata[k] = self.getMetadata(k)
                
        return allmetadata
    
    def addToList(self,listname,value):
        if value==None:
            return
        if not self.isList(listname) or not listname in self.metadata:
            # Calling addToList to a non-list meta will overwrite it.
            self.metadata[listname]=[]
        # prevent duplicates.
        if not value in self.metadata[listname]:
            self.metadata[listname].append(value)

    def isList(self,listname):
        'Everything set with an include_in_* is considered a list.'
        return ( self.isValidMetaEntry(listname) and self.metadata.has_key(listname) \
                  and isinstance(self.metadata[listname],list) )
    
    def getList(self,listname,
                includelist=[]):
        #print("getList(%s,%s)"%(listname,includelist))
        retlist = []
        
        if not self.isValidMetaEntry(listname):
            return retlist

        if not self.isList(listname):
            retlist = [self.getMetadata(listname)]
        else:
            retlist = self.getMetadataRaw(listname)

        if retlist:
            if listname in ('author','authorUrl'):
                # need to retain order for author & authorUrl so the
                # two match up.
                return retlist
            else:
                # remove dups and sort.
                return sorted(list(set(retlist)))
        else:
            return []

    def formatFileName(self):
        values = origvalues = self.getAllMetadata()
        # fall back default:
        template="${siteabbrev}_${paperId}.pdf"
        return string.Template(template).substitute(values).encode('utf8')
